package com.remote.face_remote.listener;

import com.remote.face_remote.mapper.RegisterMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
public class RegisterListener {
    @Autowired
    RegisterMapper registerMapper;

    private static final Logger log = LoggerFactory.getLogger(RegisterListener.class);

    @RabbitListener(bindings = @QueueBinding(
            value =  @Queue(name = "face.register"),
            exchange = @Exchange(name = "faceExchange",type = ExchangeTypes.DIRECT),
            key = "register"
    ))
    public void listenRegister(String id) throws SQLException, IOException {
        System.out.println("收到消息：" + id);
        String grade = id.substring(0, 4);
        // 拉取图片
        var images = registerMapper.register(id);

        for (int i = 0; i < images.size(); i++) {

            InputStream inputStream = new ByteArrayInputStream(images.get(i).image());
            // create folder
            File file = new File(".\\register_picture\\" + grade + "\\" + id);
            if (!file.exists()) {
                file.mkdirs();
            }
            try (OutputStream outputStream = new FileOutputStream(".\\register_picture\\" + grade + "\\" + id + "\\" + i + ".jpg")) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        }
        //调用python脚本训练模型
        Process proc = Runtime.getRuntime().exec(new String[]{"./python/venv/Scripts/python.exe", "./python/train.py", id});



        // 删除文件夹
        File file = new File(".\\register_picture\\" + id);
        if (file.exists()) {
            File[] files = file.listFiles();
            for (File f : files) {
                f.delete();
            }
            file.delete();
        }
        // log
        log.info("Register success");
    }

}
